/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.branchstores;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.BranchPurchaseState;
import com.qinyeit.serviceapp.entity.enums.BranchPurchaseType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.branchstores.BranchPurchaseOrderDetailService;
import com.qinyeit.serviceapp.service.branchstores.BranchPurchaseOrderService;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.service.materials.PurchaseSpecService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.stores.StockService;
import com.qinyeit.serviceapp.service.stores.WarehouseService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: BranchPurchaseOrdersController <br/>
 * Function: branchPurchaseOrder [门店采购订单] <br/>
 * date: 2018-11-29 17:12:44 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/branchstores/branchPurchaseOrders")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_branchPurchaseOrder:read",name ="门店采购订单",deleteAble = false)
public class BranchPurchaseOrdersController extends BaseManagementController{

	@Autowired
	private BranchPurchaseOrderService branchPurchaseOrderService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private BranchPurchaseOrderDetailService branchPurchaseOrderDetailService;
	@Autowired
    private PurchaseSpecService purchaseSpecService;
	@Autowired
    private WarehouseService warehouseService;
	@Autowired
    private StockService stockService;
	@Autowired
    private MaterialService materialService;

	private final String [] keys = {"id","no","type","branchId","branchName","supplierId","supplierName","warehouseName","address","purchaser","purchaseTime","checker","checkTime","sender","sendTime","acceptTime","amount","state","remark","createAt"};

    @RequiresPermissions("management_branchPurchaseOrder:show")
    @PermissionInfo(code = "management_branchPurchaseOrder:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<BranchPurchaseOrder> branchPurchaseOrderPage = branchPurchaseOrderService.findAll(searchable);
        QyMap map = QyMap.map("branchPurchaseOrderPage",JSONUtils.include(branchPurchaseOrderPage,new Class[]{BranchPurchaseType.class,BranchPurchaseState.class}, keys));
        //订单类型
        map.setv("types", BranchPurchaseType.values());
        //状态
        map.setv("states", BranchPurchaseState.values());

        //采购门店
        initFormDate(map);
        return ok("查询成功",map );
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long id){
        QyMap map=QyMap.NEW();
        if(id==null){
            map.setv("branchPurchaseOrder",JSONUtils.include(new BranchPurchaseOrder(), keys));
        }else {
            BranchPurchaseOrder order = branchPurchaseOrderService.findById(id);
            map.setv("branchPurchaseOrder",JSONUtils.include(order,keys));
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("order.id_eq",id);
            List<BranchPurchaseOrderDetail> detailList =  branchPurchaseOrderDetailService.findWithSort(searchable);
            List<QyMap> specList = Lists.newArrayList();
            QyMap item = null;
            Material material ;
            if(CollectionUtils.isNotEmpty(detailList)){
                for (BranchPurchaseOrderDetail detail : detailList) {
                    material = materialService.getMaterialByUUid(detail.getUuid(),CurrentAccountUtils.getAuthenticatedMerchantGroupID());
                    detail.setWarehouses(stockService.getWarehouses(material.getId(),CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
                    item = QyMap.NEW();
                    item.setv("id", detail.getSpecId());
                    item.setv("no", detail.getNo());
                    item.setv("unit", detail.getStockUnit());
                    item.setv("nameValue", detail.getName());
                    item.setv("goodsSpec", detail.getMaterialSpec());
                    item.setv("purchaseSpec", detail.getPurchaseSpec());
                    item.setv("purchaseUnit", detail.getPurchaseUnit());
                    item.setv("purchasePrice", detail.getPurchasePrice());
                    item.setv("name", detail.getName());
                    if(com.qinyetech.springstage.core.lang.StringUtils.isNotBlank(item.getString("code"))){
                        item.setv("goodcode",item.getString("code").substring(1,item.getString("code").indexOf(",",2)));
                        //将编码逗号分隔为数组
                        item.setv("goodcodes", org.apache.commons.lang3.StringUtils.split(item.getString("code"),","));
                    }else {
                        item.setv("goodcode","");
                        item.setv("goodcodes",null);
                    }
                    specList.add(item);
                }
            }
            map.setv("detailList",JSONUtils.include(detailList,"id","specId","no","name","materialSpec","stockUnit","purchaseSpec","purchaseUnit"
                    ,"purchaseCount","purchasePrice","sendCount","sendPrice","acceptCount","acceptPrice","groupRemark","branchRemark","stockId","stockName",
                    "warehouses","uuid"));
            map.setv("materials",specList);
        }
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_branchPurchaseOrder:create")
    @PermissionInfo(code = "management_branchPurchaseOrder:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject branchPurchaseOrder, BindingResult bindingResult){
//        if(branchPurchaseOrderService.exists(buildExists(null, "no", branchPurchaseOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        branchPurchaseOrderService.saveData(branchPurchaseOrder,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute BranchPurchaseOrder branchPurchaseOrder){
        return ok("查询成功", JSONUtils.include(branchPurchaseOrder, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute BranchPurchaseOrder branchPurchaseOrder){
        QyMap map=QyMap.NEW();
        map.setv("branchPurchaseOrder",JSONUtils.include(branchPurchaseOrder, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_branchPurchaseOrder:update")
    @PermissionInfo(code = "management_branchPurchaseOrder:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid BranchPurchaseOrder branchPurchaseOrder,BindingResult bindingResult){
//        if(branchPurchaseOrderService.exists(buildExists(null, "no", branchPurchaseOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        branchPurchaseOrderService.update(branchPurchaseOrder);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_branchPurchaseOrder:destory")
    @PermissionInfo(code = "management_branchPurchaseOrder:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        BranchPurchaseOrder order = branchPurchaseOrderService.findById(id);
        if (order==null){
           return fail("订单不存在");
        }else if (order.getMerchantGroupId()!=CurrentAccountUtils.getAuthenticatedMerchantGroupID()){
            return fail("订单不存在");
        }else if (order.getState()!=BranchPurchaseState.NOAUDIT){
            return fail("订单不允许删除");
        }
        //删除明细
        branchPurchaseOrderService.deletedAll(id);
//        branchPurchaseOrderService.logicDelete(id);

        return ok("删除成功", null);
    }

    @RequiresPermissions("management_branchPurchaseOrder:reject")
    @PermissionInfo(code = "management_branchPurchaseOrder:reject",name ="驳回",deleteAble = false)
    @GetMapping("/reject")
    public ResponseResult<String> reject(String no){
        if (StringUtils.isBlank(no)){
            return fail("单号为空");
        }

        //删除明细
        branchPurchaseOrderService.reject(no,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("驳回成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            BranchPurchaseOrder branchPurchaseOrder = branchPurchaseOrderService.findById(Long.valueOf(id));
            model.addAttribute(branchPurchaseOrder);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //直配门店
        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
        qyMap.setv("districts",list);
    }

}